import { Input, InputProps } from 'antd'
import React from 'react'

interface IMobileInput extends InputProps {
  value: string
  onValueChange(value: string): void
  onBlur?(): void
}

export default function MobileInput(props: IMobileInput) {
  const { value, onValueChange, onBlur, ...rest } = props

  function onChange(e: any) {
    const { value } = e.target
    const reg = /^\d*(\d*)?$/
    if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
      onValueChange(value)
    }
  }

  // '.' at the end or only '-' in the input box.
  function onInputBlur() {
    let valueTemp = value
    if (value.charAt(value.length - 1) === '.' || value === '-') {
      valueTemp = value.slice(0, -1)
    }
    onValueChange(valueTemp.replace(/0*(\d+)/, '$1'))
    if (onBlur) {
      onBlur()
    }
  }

  return <Input {...rest} value={value} onChange={onChange} onBlur={onInputBlur} />
}
